package cn.bugstack.job;

import cn.bugstack.service.IOrderService;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


/*
 * 检测未接收到或未正确处理的支付回调通知
 */

@Slf4j
@Component
public class NoPayNotifyOrderJob {
    @Resource
    private IOrderService orderService;
    @Resource
    private AlipayClient alipayClient;

    @Scheduled(cron = "0/3 * * * * ?")
    public void exec(){
        // 回调失败，使用定时任务主动去查询回调失败订单
        try{
            log.info("任务；检测未接收到或未正确处理的支付回调通知");
            // 查询到处于等待支付状态超过1分钟的订单id
            List<String> orderIds = orderService.queryNoPayNotifyOrder();
            if(orderIds==null||orderIds.isEmpty()) return;

            for(String orderId : orderIds){
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel bizModel = new AlipayTradeQueryModel();
                bizModel.setOutTradeNo(orderId);
                request.setBizModel(bizModel);

                // 调用支付宝查询接口
                AlipayTradeQueryResponse response = alipayClient.execute(request);
                String code = response.getCode();
                // 判断状态码
                if("10000".equals(code)){
                    // 支付成功
                    orderService.changeOrderPaySuccess(orderId);
                }
            }

        }catch (Exception e){
            log.error("检测未接收到或未正确处理的支付回调通知失败", e);
        }
    }


}
